/*
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var Repayment = {
    transaction_currency: null,
    usd_rate: null,
    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;

        Calendar.setup({
            inputField : "pay_date",
            trigger    : "pay_date_btn",
            onSelect   : function() { this.hide() },
            dateFormat: "%Y-%m-%d",
            showTime: false,
            animation: true
        });

        //self.transaction_currency = $('#gbl_currency').val();
        self.usd_rate = parseFloat($('#conversion_rate').val());
        $("#form  #usd_rate").val(self.usd_rate);

        $('#conversion_rate').focusout(function () {
            //self.transaction_currency = $('#gbl_currency').val();
            self.usd_rate = parseFloat($('#conversion_rate').val());
            $("#form  #currency").val(self.transaction_currency );
            $("#form  #usd_rate").val(self.usd_rate);
        });


        $('#original_paid_amount').focusout(function () {
            var currency = $('#form #paid_amount_currency').val();
            self.getPayAmount(currency, $(this).val());
        });

        $('#paid_amount_currency').change(function () {
            var amt = $('#form #original_paid_amount').val();
            self.getPayAmount($(this).val(), amt);
        });


        /************ Credit Payment ********************/

        $("#form #sale_id").change(function () {
            //$(this).applyClear();
            self.updateCreditDetail($(this).val());
        });


        $("#form #c_customer_id").change(function(){
            var customer_id = $(this).val();
            var last_sale_id = $("#set_default_sale").val();
            if(typeof global_creditors[customer_id] == "undefined"){
                return;
            }
            var customer_credit_data = global_creditors[customer_id]['Sale'];
            //console.log(customer_credit_data)
            var select = document.getElementById('sale_id');
            select.options.length = 0;
            for(nx in customer_credit_data){
                var opt = document.createElement('option');
                //console.log(customer_credit_data[nx].id)
                opt.value = customer_credit_data[nx].id;
                //if(customer_credit_data[nx].vehicle_no){
                    opt.text = customer_credit_data[nx].purchased_date+" ("+customer_credit_data[nx].invoice_number+")";
                //}
                //else{
                    //opt.text = customer_credit_data[nx].purchased_date;
                //}

                try{ //Standard
                    select.add(opt,null) ;
                }
                catch(error){ //IE Only
                    select.add(opt) ;
                }
            }
            //select.options[last_sale_id].selected = true;
            $("#sale_id").val(last_sale_id);
            //reapply custom select to update the options
            jLib.refreshCustomElement($("#sale_id"),'select');

            $("#form #sale_id").change();
        });

        $("#form #c_customer_id").change();

        $('#save-btn').click(function () {
            self.saveCreditPayment();
        });
        $('#cancel-btn').click(function () {
            $('.credit-detail-window ul').html('');
            $.validationEngine.closePrompt('.formError', true);
            $("#form #sale_id").change();
            document.getElementById('form').reset();
        });

        $("#form").validationEngine();

        /*$('#original_paid_amount').live('keydown',function(event) {
            if(event.which == 8 || event.which == 37 || event.which == 40 || event.which == 38 || event.which == 39){
                //allow keys for backspace, arrow keys
            }
            else{
                if ((event.which != 190 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                    console.log('prevent')
                    event.preventDefault();
                }
            }
        });*/
    },


    updateCreditDetail:function (sale_id) {
        var self = this;

        $('.credit-detail-window ul').html('');

        var customer_id = $("#c_customer_id").val();
        if(typeof sale_id == "undefined"){
            sale_id = $("#form #sale_id").val();
        }
        //console.log(customer_id);
        //console.log(sale_id);

        var data = global_creditors[customer_id]['Sale'][sale_id];
        //console.log(data);
        var currency = data['currency'];
        var purchase_type = data['purchase_type'];

        self.transaction_currency = currency;
        $("#trans_curr_lbl").html( self.transaction_currency);
        $("#form  #currency").val(self.transaction_currency );
        $("#form  #usd_rate").val(self.usd_rate);
        $("#form  #paid_amount_currency").val(currency);
        $("#form  #paid_amount_currency").change();
        //$("#amt_tendered_txt").html("Amount Tendered "+currency);

        var items = '';
        if(data.hasOwnProperty('SaleItem')){
            for(var x in data['SaleItem']){
                items += data['SaleItem'][x]['Item']['name']+'(qty x'+data['SaleItem'][x]['quantity']+'),&nbsp;&nbsp;'
            }
        }

        var totalpayment = 0.00;
        if(data.hasOwnProperty('SaleCreditPayment')){
            for(var x in data['SaleCreditPayment']){
                totalpayment += parseFloat(data['SaleCreditPayment'][x]['paid_amount']);
            }
        }

        var tl_inerest_raw = 0.00;
        var opening_bal_raw = 0.00;
        if(data.hasOwnProperty('Amortization')){
            tl_inerest_raw = parseFloat(data['Amortization']['tl_inerest_raw']);
            opening_bal_raw = parseFloat(data['Amortization']['opening_bal_raw']);
        }


        //Monthly Installments
        //var mth_inst =  (parseFloat(data['opening_bal'])) / parseInt(data['duration_in_month']) ;
        var mth_inst =  jLib.getMonthlyPayment(data['interest'],data['duration_in_month'],data['opening_bal'],data['tenor'],data['interest_rate_decimal_places'],purchase_type) ;

        // Outstanding balance
        var prin_bal = (parseFloat(data['opening_bal'])) -  totalpayment;
        var total_bal = (opening_bal_raw + tl_inerest_raw) -  totalpayment;

        var li = $("<li />").append($("<span />").addClass('label').html('<b>Sales Number :</b>')).append($("<span />").addClass('value').html(data['invoice_number']));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Date of Purchase :</b>')).append($("<span />").addClass('value').html(data['purchased_date']));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Purchase Type :</b>')).append($("<span />").addClass('value').html(data['purchase_type']));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Duration in Month :</b>')).append($("<span />").addClass('value').html(data['duration_in_month']));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Items Purchased :</b>')).append($("<span />").addClass('value').html(items));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Vehicle Number :</b>')).append($("<span />").addClass('value').html(data['vehicle_no']));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Cost :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(data['cost'],'money')));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Interest % :</b>')).append($("<span />").addClass('value').html(data['interest']));
        $('.credit-detail-window ul').append(li);
        /*var li = $("<li />").append($("<span />").addClass('label').html('Interest Amount:')).append($("<span />").addClass('value').html(data['interest_amount']));
        $('.credit-detail-window ul').append(li);*/
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Principal :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(data['principal'],'money')));
        $('.credit-detail-window ul').append(li);

        var li = $("<li />").append($("<span />").addClass('label').html('<b>Discount % :</b>')).append($("<span />").addClass('value').html(data['discount']));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Deposited :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(data['deposit'],'money')));
        $('.credit-detail-window ul').append(li);

        var li = $("<li />").append($("<span />").addClass('label').html('<b>Opening Bal. :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(data['opening_bal'],'money')));
        $('.credit-detail-window ul').append(li);

        var li = $("<li />").append($("<span />").addClass('label').html('<b>Monthly Installment :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(mth_inst,'money')));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Total Instalments paid :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(totalpayment,'money')));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Total Interest :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(tl_inerest_raw,'money')));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Outstanding Principal :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(prin_bal,'money')));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Total Balance :</b>')).append($("<span />").addClass('value').html(currency+" "+jLib.formatNumber(total_bal,'money')));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Last Paid Month :</b>')).append($("<span />").addClass('value').html(data['last_paid_date']));
        $('.credit-detail-window ul').append(li);
        var li = $("<li />").append($("<span />").addClass('label').html('<b>Next Credit Date :</b>')).append($("<span />").addClass('value').html(data['next_credit_date']));
        $('.credit-detail-window ul').append(li);



        $("#form #amt_expected_txt span b").html(currency+" "+jLib.formatNumber(mth_inst,'money'));

        $("#form #pay_date").val(data['next_credit_date']);

        self.getPayAmount('$',0.00);
    },

    getPayAmount: function(currency, amt){
        var self = this;
        amt = parseFloat(amt);
        if(currency == self.transaction_currency){
            $("#form #amt_tendered_rate_txt").hide();
        }
        else{
            if(self.transaction_currency == '$' && currency == 'GHc'){//Covert to dollar
                amt = amt / self.usd_rate;
            }
            else if(self.transaction_currency == 'GHc' && currency == '$'){//Convert to Cedi
                amt = amt * self.usd_rate;
            }
            $("#form #amt_tendered_rate_txt").show();
        }

        $("#form #amt_tendered_rate_txt span b").html(''+self.transaction_currency+' '+amt);

        return amt;
    },

    saveCreditPayment:function () {
        var self = this;

        /* Validate the form*/
        var validationStatus = $('#form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {

            var amt = $("#form #original_paid_amount").val();
            if(amt == 0){
                jLib.serverError("The amount tendered must be greater than 0");
                return false;
            }

            jLib.showFormLoading();

            var currency = $('#form #paid_amount_currency').val();

            $("#form #paid_amount").val(self.getPayAmount(currency,amt));

            var url = $('#add-edit-url').val();
            var query = 'model=SaleCreditPayment&'+ $('#form').serialize();
            /* Send the data to the server and handle the server response */

            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {
                        /* Alert the user that the server response*/
                        jLib.message(txt, 'success');
                        var customer_id = $('#form #c_customer_id').val();
                        var sale_id = $('#form #sale_id').val();
                        var data = {
                            id: response.data.id,
                            sale_id:sale_id,
                            paid_amount:$('#form #paid_amount').val(),
                            pay_date:$('#form #pay_date').val(),
                            pay_type:$('#form #pay_type').val(),
                            comments:$('#form #comments').val()
                        };

                        global_creditors[customer_id]['Sale'][sale_id]['last_paid_date'] = response.data.last_paid_date;
                        global_creditors[customer_id]['Sale'][sale_id]['next_credit_date'] = response.data.next_credit_date;
                        global_creditors[customer_id]['Sale'][sale_id]['SaleCreditPayment'].push(data);

                        //Initate print reciept
                        var print_reciept = $("#form #original_paid_amount").val();
                        if($('#print_receipt').attr('checked')){
                            var action = $('#print-receipt-url').val();
                            var url = action+'/'+response.data.id;

                            window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
                        }

                        location.reload();
                        //Reset the form
                        //$('#cancel-btn').click();
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    }


};

/* when the page is loaded */
$(document).ready(function () {
    Repayment.init();
});